package com.qiye.livevideo.config.aop;

import com.qiye.livevideo.common.CodeMsg;
import com.qiye.livevideo.common.ResultInfo;
import com.qiye.livevideo.common.RetConstant;
import com.qiye.livevideo.model.ApiCount;
import com.qiye.livevideo.service.ApiCountService;
import com.qiye.livevideo.utils.DateUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * Created on 2019/5/3.
 * aop切面---  控制controller层和service层相关方法
 *
 * @author meishijun
 */
@Aspect
@Configuration
public class AspectMethod {

    private static final Logger log = LoggerFactory.getLogger(AspectMethod.class);

    @Resource
    private ApiCountService apiCountService;

    /**
     * Controller层切点---限制阿里云关键api调用次数
     */
    @Pointcut("@annotation(com.qiye.livevideo.config.aop.ControllerApiCall)")
    public void controllerAspect() {

    }


    /**
     * 拦截方法的执行
     *
     * @param pjp
     * @return
     */
    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        //你的校验成功执行方法,失败方法就不用执行了
        if (verification()) {
            return pjp.proceed();
        } else {
            //可以返回你失败的信息也可以直接抛出校验失败的异常
            log.info("一分钟内调用次数超过1000次");
            return ResultInfo.error(CodeMsg.SERVER_EXCEPTION, "一分钟内调用次数不能超过1000次");
        }
    }


    /**
     * 校验数据并进行次数的记录
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean verification() {
        try {
            //获取当前的分钟数
            String now = DateUtils.formatDateByPattern(new Date(), "yyyy-MM-dd HH:mm") + ":00";
            ApiCount apiCount = apiCountService.selectByCreateTime(now);
            if (apiCount == null) {
                //当前分钟内第一次调用
                ApiCount api = new ApiCount();
                api.setCreateTime(DateUtils.formatDateByString(now));
                api.setApiCount(1);
                apiCountService.insert(api);
                return true;
            } else {
                if (apiCount.getApiCount() != null && RetConstant.API_COUNT > apiCount.getApiCount()) {
                    apiCountService.updateCountById(apiCount.getId());
                    return true;
                } else {
                    return false;
                }
            }
        } catch (Exception e) {
            log.info("校验接口调用次数时异常：", e.getMessage());
            return false;
        }
    }


}
